package com.example.pyphone3;

import android.Manifest;
import android.app.AlertDialog;
import android.app.DatePickerDialog;
import android.app.Dialog;
import android.content.BroadcastReceiver;
import android.content.ComponentName;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.ServiceConnection;
import android.content.pm.PackageManager;
import android.net.Uri;
import android.os.Bundle;
import android.os.Environment;
import android.os.IBinder;
import android.os.Looper;
import android.telephony.SmsManager;
import android.telephony.TelephonyManager;
import android.util.Log;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.Button;
import android.widget.DatePicker;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;

import androidx.annotation.NonNull;
import androidx.appcompat.app.AppCompatActivity;
import androidx.core.app.ActivityCompat;

import org.apache.commons.lang3.StringUtils;
import org.java_websocket.handshake.ServerHandshake;

import java.io.BufferedReader;
import java.io.File;
import java.io.InputStreamReader;
import java.net.URI;
import java.net.URL;
import java.net.URLConnection;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import SQLite.SQLFunction;
import config.GetHttpRequester;

public class FragmentCallActivity extends AppCompatActivity {
    private JWebSocketClient client;
    private JWebSocketClientService.JWebSocketClientBinder binder;
    private JWebSocketClientService jWebSClientService;
    private static final int MY_PERMISSIONS_REQUEST_SEND_SMS = 1;
    private static String MEDIA_MOUNTEDs = "";
    private ChatMessageReceiver chatMessageReceiver;
    private static String nowMtime = DateTimeKit.now().substring(0, 7).replace("-", "");
    private static String nowMtimey = DateTimeKit.now().substring(0, 7);
    private static String nowMtimed = DateTimeKit.now().substring(0, 10);
    private static final String TAG = FragmentCallActivity.class.getSimpleName();
    private static int duplicateSubmission = 0;
    SimpleDateFormat sdd = new SimpleDateFormat("yyyy-MM-dd");
    SimpleDateFormat sdfy = new SimpleDateFormat("yyyy-MM");
    int mYear, mMonth, mDay;
    TextView dateDisplay;
    final int DATE_DIALOG = 1;
    private static final int SEND_SMS = 100;
    private static String EnvironmentPath = Environment.getExternalStorageDirectory().getPath();
    Button btn_sql;
    String postResult = "0";
    String username = null;
    String password = null;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        new Thread(wsRun).start();
        new Thread(listenerSDCardRun).start();
    }

    public String getid() {
        /**【初始化数据库】**/
        SQLFunction.initTable(FragmentCallActivity.this);
        SQLFunction function = new SQLFunction();
        String where1 = postResult;
        String where2 = username;
        String where3 = password;
        ArrayList<HashMap<String, String>> list = new ArrayList<>();
        list = function.query(FragmentCallActivity.this, where1, where2, where3);
        if (list.size() != 0) {
            setContentView(R.layout.fragment_call);
            postResult = list.get(0).get("_id");
            return list.get(0).get("_id");
        } else {
            return "";
        }
    }

    public String GetPhoneNum() {
        try {
            TelephonyManager tm = (TelephonyManager) this
                    .getSystemService(Context.TELEPHONY_SERVICE);
            if (ActivityCompat.checkSelfPermission(this, Manifest.permission.READ_SMS) != PackageManager.PERMISSION_GRANTED && ActivityCompat.checkSelfPermission(this, Manifest.permission.READ_PHONE_NUMBERS) != PackageManager.PERMISSION_GRANTED && ActivityCompat.checkSelfPermission(this, Manifest.permission.READ_PHONE_STATE) != PackageManager.PERMISSION_GRANTED) {
                return "";
            }
            String phoneId = tm.getLine1Number();
            return phoneId;
        } catch (Exception e) {
            return "";
        }
    }

    public String clickgettelNum(View view) {
        TelephonyManager tm = (TelephonyManager) this.getSystemService(Context.TELEPHONY_SERVICE);
        String deviceid = tm.getDeviceId();
        if (ActivityCompat.checkSelfPermission(this, Manifest.permission.READ_SMS) != PackageManager.PERMISSION_GRANTED && ActivityCompat.checkSelfPermission(this, Manifest.permission.READ_PHONE_NUMBERS) != PackageManager.PERMISSION_GRANTED && ActivityCompat.checkSelfPermission(this, Manifest.permission.READ_PHONE_STATE) != PackageManager.PERMISSION_GRANTED) {
            return "TODO";
        }
        String tel = tm.getLine1Number();//手机号码
        String imei = tm.getSimSerialNumber();
        String imsi = tm.getSubscriberId();
        return tel;
    }

    public void clicksjk(View view) {
        int id = view.getId();
        switch (id) {
            case R.id.btn_sql:
                DB_i_u_d_s();
                break;
        }
    }

    public void clickLogin(View view) throws Exception {
        int i = 0;
        EditText usenameText = (EditText) findViewById(R.id.et_usename);
        EditText passwordText = (EditText) findViewById(R.id.et_password);
        username = usenameText.getText().toString();
        password = passwordText.getText().toString();
        new Thread(getHttpRun).start();
        Thread.sleep(2000);
        if (!postResult.equals("00") && !postResult.equals("0")) {
            setContentView(R.layout.fragment_call);
            new Thread(wsRun).start();
            new Thread(listenerSDCardRun).start();
        } else {
            Toast.makeText(getApplicationContext(), "用户名或密码不正确！", Toast.LENGTH_SHORT).show();
        }
    }

    Runnable getHttpRun = new Runnable() {
        @Override
        public void run() {
            Map<String, String> params = new HashMap<>();
            params.put("username", username);
            params.put("password", password);
            try {
                postResult = GetHttpRequester.getHttp("http://phone.yiyatest.cn/call/login", params);
                postResult = postResult + "";
                Object[] data = {postResult, username, password};
                if (!postResult.equals("0")) {
                    SQLFunction function = new SQLFunction();
                    String where1 = postResult;
                    String where2 = username;
                    String where3 = password;
                    ArrayList<HashMap<String, String>> list = new ArrayList<>();
                    list = function.query(FragmentCallActivity.this, where1, where2, where3);
                    if (list.size() != 0) {
                        for (int i = 0; i < list.size(); i++) {
                            Log.i("TAG:", "从数据库中拿到的数据 _ID为：" + list.get(i).get("_id"));
                            Log.i("TAG:", "从数据库中拿到的数据 userid：" + list.get(i).get("userid"));
                            Log.i("TAG:", "从数据库中拿到的数据name为：" + list.get(i).get("name"));
                            Log.i("TAG:", "从数据库中拿到的数据info为：" + list.get(i).get("info"));
                        }
                    } else {
//                        function.insert(MainActivity.this, data);
                    }
                } else {
                    postResult = "00";
                }
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    };

    Runnable listenerSDCardRun = new Runnable() {
        @Override
        public void run() {
            String path2 = Environment.getExternalStorageDirectory().getPath();
            String path = null;
            File file1 = new File(path2 + "/Sounds/CallRecord");
            if (file1.exists()) {
                SDCardListener listener = new SDCardListener(path2 + "/Sounds/CallRecord");
                listener.startWatching();//开始监听
            } else {
                file1 = new File(path2 + "/MIUI/sound_recorder/call_rec");
                if (file1.exists()) {
                    SDCardListener listener = new SDCardListener(path2 + "/MIUI/sound_recorder/call_rec");
                    listener.startWatching();//开始监听
                } else {
                    file1 = new File(path2 + "/Record/Call");
                    if (file1.exists()) {
                        SDCardListener listener = new SDCardListener(path2 + "/Record/Call");
                        listener.startWatching();//开始监听
                    } else {
                        file1 = new File(path2 + "/Pictures");
                        if (file1.exists()) {
                            SDCardListener listener = new SDCardListener(path2 + "/Pictures");
                            listener.startWatching();//开始监听
                        }
                    }
                }
            }
        }
    };

    /**
     * 【操作数据库的方法】
     **/
    private void DB_i_u_d_s() {
        EditText usenameText = (EditText) findViewById(R.id.et_usename);
        EditText passwordText = (EditText) findViewById(R.id.et_password);
        String aaa = usenameText.getText() + "";
        SQLFunction function = new SQLFunction();
        Log.i("TAG:", "插入数据！");
        Object[] data = {"1111111", "root", "123456"};
//        function.insert(FragmentCallActivity.this, data);

        /**
         * Log.i("TAG:","通过id来修改数据！");
         *String name = "sale";
         *String info = "TestSale";
         *int _id = 7;
         *Object[]data = {name,info,_id};
         *function.update(MainActivity.this,data);
         * */

        /**
         * Log.i("TAG:","通过id来删除数据！");
         *int d_id = 2;
         *Object[] did = {d_id};
         *function.delete(MainActivity.this,did);
         * */
        Log.i("TAG:", "查询数据！");
        String where1 = null;
        String where2 = null;
        ArrayList<HashMap<String, String>> list = new ArrayList<>();
        list = function.query(FragmentCallActivity.this, where1, where2, where2);
        if (list != null) {
            for (int i = 0; i < list.size(); i++) {
                Log.i("TAG:", "从数据库中拿到的数据 _ID为：" + list.get(i).get("_id"));
                Log.i("TAG:", "从数据库中拿到的数据 userid：" + list.get(i).get("userid"));
                Log.i("TAG:", "从数据库中拿到的数据name为：" + list.get(i).get("name"));
                Log.i("TAG:", "从数据库中拿到的数据info为：" + list.get(i).get("info"));
            }
        } else {
            Log.i("TAG:", "从数据库中没有拿到数据！");
        }
    }

    @Override
    public void onResume() {
        super.onResume();
    }

    // v: 代表你点击的控件
    public void call(View view) {
        EditText editText = (EditText) findViewById(R.id.et_input_num);
        String phone_number = editText.getText().toString(); // 获取用户输入的手机号
        phone_number = phone_number.trim();//删除字符串首部和尾部的空格
        Toast.makeText(this, phone_number, Toast.LENGTH_LONG);
        if (phone_number != null && !phone_number.equals("")) {
            Intent t = new Intent();            //调用系统的拨号服务实现电话拨打功能 打电话 Intent : 意图.我想去做一件事
            t.setAction(Intent.ACTION_CALL); // Action:动作.我具体想做什么事 Intent.ACTION_DIAL: 激活拨号界面 Intent.ACTION_CALL: 直接拨打电话
            t.setData(Uri.parse("tel:" + phone_number));  // Data: 数据.具体的动作所需要的附加数据 封装一个拨打电话的intent，并且将电话号码包装成一个Uri对象传入
            startActivity(t);// 通知系统你去帮我干活吧
        }
    }

    //发送短信
    public void sendSMSS(View view) {
        EditText editText = (EditText) findViewById(R.id.et_input_num);
        EditText SMSSText = (EditText) findViewById(R.id.SMSS_input_content);
        String phone = editText.getText().toString(); // 获取用户输入的手机号
        String content = SMSSText.getText().toString();
        if (!StringUtils.isEmpty(content) && !StringUtils.isEmpty(phone)) {
            SmsManager manager = SmsManager.getDefault();
            ArrayList<String> strings = manager.divideMessage(content);
            for (int i = 0; i < strings.size(); i++) {
                manager.sendTextMessage(phone, null, content, null, null);
            }
            Toast.makeText(FragmentCallActivity.this, "发送成功", Toast.LENGTH_SHORT).show();
        } else {
            Toast.makeText(this, "手机号或内容不能为空", Toast.LENGTH_SHORT).show();
            return;
        }
    }

    public void cwss() {
        try {
            String url = "ws://phone.yiyatest.cn/callWebSocket/" + postResult;
            URI uri = new URI(url);
            JWebSocketClient mWs = new JWebSocketClient(uri) {
                @Override
                public void onOpen(ServerHandshake serverHandshake) {
                    System.out.println(serverHandshake);
                }

                @Override
                public void onMessage(String s) {
                    if ("dk".equals(s)) {
                        cws();
                    } else {
                        String phone_number = s;
                        phone_number = phone_number.trim();
                        EditText editText = (EditText) findViewById(R.id.et_input_num);
                        editText.setText(phone_number);
                        if (phone_number != null && !phone_number.equals("") && !phone_number.equals("dk")) {
                            Intent t = new Intent();
                            t.setAction(Intent.ACTION_CALL);
                            t.setData(Uri.parse("tel:" + phone_number));
                            startActivity(t);
                        }
                    }
                }

                @Override
                public void onClose(int i, String s, boolean b) {
                    cws();
                    System.out.println(s);
                }

                @Override
                public void onError(Exception e) {
                    System.out.println(e);
                }
            };
            mWs.connect();
            System.out.println("haha");
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    public void cws() {
        try {
            String url = "ws://phone.yiyatest.cn/callWebSocket/" + postResult;
            URI uri = new URI(url);
            JWebSocketClient mWs = new JWebSocketClient(uri) {
                @Override
                public void onOpen(ServerHandshake serverHandshake) {
                    System.out.println(serverHandshake);
                }

                @Override
                public void onMessage(String s) {
                    if ("dk".equals(s)) {
                        cws();
                    } else {
                        String phone_number = s;
                        phone_number = phone_number.trim();
                        EditText editText = (EditText) findViewById(R.id.et_input_num);
                        editText.setText(phone_number);
                        if (phone_number != null && !phone_number.equals("") && !phone_number.equals("dk")) {
                            Intent t = new Intent();
                            t.setAction(Intent.ACTION_CALL);
                            t.setData(Uri.parse("tel:" + phone_number));
                            startActivity(t);
                        }
                    }
                }

                @Override
                public void onClose(int i, String s, boolean b) {
                    cws();
                    System.out.println(s);
                }

                @Override
                public void onError(Exception e) {
                    System.out.println(e);
                }
            };
            mWs.connect();
            System.out.println("haha");
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    @Override
    protected Dialog onCreateDialog(int id) {
        switch (id) {
            case DATE_DIALOG:
                return new DatePickerDialog(this, mdateListener, mYear, mMonth, mDay);
        }
        return null;
    }

    private class ChatMessageReceiver extends BroadcastReceiver {
        @Override
        public void onReceive(Context context, Intent intent) {
            String message = intent.getStringExtra("message");
            Log.e(TAG, "-----接收服务端数据" + message);
        }
    }

    private ServiceConnection serviceConnection = new ServiceConnection() {
        @Override
        public void onServiceConnected(ComponentName componentName, IBinder iBinder) {
            //服务与活动成功绑定
            Log.e(TAG, "服务与活动成功绑定");
            binder = (JWebSocketClientService.JWebSocketClientBinder) iBinder;
            jWebSClientService = binder.getService();
            client = jWebSClientService.client;
        }

        @Override
        public void onServiceDisconnected(ComponentName componentName) {
            Log.e(TAG, "服务与活动成功断开");
        }
    };

    /**
     * 设置日期利用StringBuffer追加
     */
    public void display() {
        dateDisplay.setText(new StringBuffer().append(mMonth + 1).append("-").append(mDay).append("-").append(mYear).append(" "));
    }

    private DatePickerDialog.OnDateSetListener mdateListener = new DatePickerDialog.OnDateSetListener() {
        @Override
        public void onDateSet(DatePicker view, int year, int monthOfYear,
                              int dayOfMonth) {
            mYear = year;
            mMonth = monthOfYear;
            mDay = dayOfMonth;
            display();
        }
    };

    Runnable wsRun = new Runnable() {
        @Override
        public void run() {
            cws();
        }
    };

    /**
     * 下载线程
     */
    Runnable downloadRun = new Runnable() {
        @Override
        public void run() {
            Looper.prepare();
            tkks();
            String path2 = Environment.getExternalStorageDirectory().getPath();
            String upUrl = "" + nowMtimed;
            File file1 = new File(path2 + "/Sounds/CallRecord");
//            File file1 = new File(path2 + "/Pictures/11");
            if (file1.exists()) {
                File[] subFile = file1.listFiles();
                for (int iFileLength = 0; iFileLength < subFile.length; iFileLength++) {
                    if (!subFile[iFileLength].isDirectory()) {// 判断是否为文件夹
                        String filename = subFile[iFileLength].getName();
                        File file = new File(file1.toString() + "/" + filename);
                        String cdate = sdd.format(file.lastModified());
                        if (file.exists() && cdate.equals(nowMtimed)) {
                            if (file.getName().trim().toLowerCase().endsWith(".amr")) {
                                upUrl = "https://phone.yiyatest.cn/call/uploadFileToOssAmr";
                            } else {
                                upUrl = "https://phone.yiyatest.cn/call/uploadFileToOss";
                            }
                            uploadFilesHw(upUrl, file, file.getName());
                        }
                    }
                }
            } else {
                file1 = new File(path2 + "/MIUI/sound_recorder/call_rec");
                if (file1.exists()) {
                    File[] subFile = file1.listFiles();
                    for (int iFileLength = 0; iFileLength < subFile.length; iFileLength++) {
                        if (!subFile[iFileLength].isDirectory()) {// 判断是否为文件夹
                            String filename = subFile[iFileLength].getName();
                            File file = new File(file1.toString() + "/" + filename);
                            String cdate = sdd.format(file.lastModified());
                            if (file.exists() && cdate.equals(nowMtimed)) {
                                if (file.getName().trim().toLowerCase().endsWith(".amr")) {
                                    upUrl = "https://phone.yiyatest.cn/call/uploadFileToOssAmr";
                                } else {
                                    upUrl = "https://phone.yiyatest.cn/call/uploadFileToOss";
                                }
                                uploadFilesXm(upUrl, file, file.getName());
                            }
                        }
                    }
                } else {
                    file1 = new File(path2 + "/Record/Call");
                    if (file1.exists()) {
                        File[] subFile = file1.listFiles();
                        for (int iFileLength = 0; iFileLength < subFile.length; iFileLength++) {
                            if (!subFile[iFileLength].isDirectory()) {// 判断是否为文件夹
                                String filename = subFile[iFileLength].getName();
                                File file = new File(file1.toString() + "/" + filename);
                                String cdate = sdd.format(file.lastModified());
                                if (file.exists() && cdate.equals(nowMtimed)) {
                                    if (file.getName().trim().toLowerCase().endsWith(".amr")) {
                                        upUrl = "https://phone.yiyatest.cn/call/uploadFileToOssAmr";
                                    } else {
                                        upUrl = "https://phone.yiyatest.cn/call/uploadFileToOss";
                                    }
                                    uploadFilesVivo(upUrl, file, file.getName());
                                }
                            }
                        }
                    }
                }
            }
            Toast.makeText(getApplicationContext(), "上传成功", Toast.LENGTH_SHORT).show();
            duplicateSubmission = 0;
            Looper.loop();//增加部分
        }
    };

    //上传服务器上传oss
    public void click3(View view) {
        duplicateSubmission++;
        if (duplicateSubmission == 1) {
            new Thread(downloadRun).start();
        }
    }

    public void tkks() {
        AlertDialog.Builder builder1 = new AlertDialog.Builder(this);
        builder1.setTitle("正在上传本月录音文件！");
        final String items[] = {"确定"};
        builder1.setSingleChoiceItems(items, -1, new DialogInterface.OnClickListener() {//-1代表没有条目被选中
            @Override
            public void onClick(DialogInterface dialog, int which) {
                String item = items[which]; //1.把选中的条目取出来
                Toast.makeText(getApplicationContext(), item.toString(), Toast.LENGTH_LONG).show();
                dialog.dismiss();//2.然后把对话框关闭
            }
        });
        builder1.show(); //一样要show
    }

    public class PhoneReceiver extends BroadcastReceiver {
        @Override
        public void onReceive(final Context context, Intent intent) {
            TelephonyManager manager = (TelephonyManager) context.getSystemService(context.TELEPHONY_SERVICE);
            switch (manager.getCallState()) {
                case TelephonyManager.CALL_STATE_IDLE:
                    Log.d(TAG, "***空闲状态中****");
                    break;
                case TelephonyManager.CALL_STATE_OFFHOOK:
                    Log.d(TAG, "***振铃中****");
                    break;
                case TelephonyManager.CALL_STATE_RINGING:
                    Log.d(TAG, "***通话中****");
                    break;
            }
        }
    }

    //点击按钮弹出一个单选对话框
    public void click2(View view) {
        AlertDialog.Builder builder = new AlertDialog.Builder(this);
        TelephonyManager tm = (TelephonyManager) this.getSystemService(Context.TELEPHONY_SERVICE);
        builder.setTitle("请选择您喜欢的课程");
        final String items[] = {"android", "ios", "c", "C++", "html", "C#"};
        builder.setSingleChoiceItems(items, -1, new DialogInterface.OnClickListener() {//-1代表没有条目被选中
            @Override
            public void onClick(DialogInterface dialog, int which) {
                String item = items[which]; //1.把选中的条目取出来
                Toast.makeText(getApplicationContext(), item.toString(), Toast.LENGTH_LONG).show();
                dialog.dismiss();//2.然后把对话框关闭
            }
        });
        builder.show(); //一样要show
    }

    public boolean onCreateOptionsMenu(Menu menu) { // Inflate the menu; this adds items to the action bar if it is present.
        getMenuInflater().inflate(R.menu.menu_main, menu);
        return true;
    }

    public static String testqhz(String str) {        // 去除中文
        String REGEX_CHINESE = "[\u4e00-\u9fa5]";// 中文正则
        Pattern pat = Pattern.compile(REGEX_CHINESE);
        Matcher mat = pat.matcher(str);
        System.out.println(mat.replaceAll(""));
        return mat.replaceAll("");
    }

    public static String testqzm(String str) {   // 去除英文
        str = str.replaceAll("[a-zA-Z]", "").replaceAll("@", "");
        System.out.println(str);
        return str;
    }

    /**
     * 上传图片到服务器
     *
     * @param file 包含路径
     */
    public void uploadFilesHw(String requestUrl, File file, String pnum) {
        Map<String, String> params = new HashMap<String, String>();
        params.put("pnum", file.getName());
        String fileName = file.getName().replace(" ", "");
        if (file.getName().contains("@")) {
            fileName = fileName.split("@")[1];
        }
        params.put("file", fileName);
        try {//请求普通信息
            FormFile formfile = new FormFile(fileName, file, "file", "application/octet-stream");
            boolean tf = SocketHttpRequester.post(requestUrl, params, formfile); //上传文件
            if (tf == true) {
                chageFileName(file.toString(), file.toString().replace("_aa2020", "_2020"));
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    public void uploadHw(String requestUrl, File file, String pnum) {
        Map<String, String> params = new HashMap<String, String>();
        params.put("pnum", "1111");
        params.put("file", null);
        try {//请求普通信息
            FormFile formfile = null;
            boolean tf = SocketHttpRequester.post(requestUrl, params, formfile); //上传文件
            if (tf == true) {
                chageFileName(file.toString(), file.toString().replace("_aa2020", "_2020"));
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    public void uploadFilesXm(String requestUrl, File file, String pnum) {
        Map<String, String> params = new HashMap<String, String>();
        params.put("pnum", file.getName());
        String fileName = file.getName().replace(" ", "");
        if (file.getName().contains("(")) {
            fileName = fileName.split("\\(")[1].replace(")", "");
        }
        params.put("file", fileName);
        try {//请求普通信息
            FormFile formfile = new FormFile(fileName, file, "file", "application/octet-stream");
            boolean tf = SocketHttpRequester.post(requestUrl, params, formfile); //上传文件
            if (tf == true) {
                chageFileName(file.toString(), file.toString().replace("_aa2020", "_2020"));
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    public void uploadFilesVivo(String requestUrl, File file, String pnum) {
        Map<String, String> params = new HashMap<String, String>();
        params.put("pnum", file.getName());
        String fileName = file.getName().replace(" ", "");
        if (file.getName().contains("(")) {
            fileName = fileName.split(" ")[0];
        }
        params.put("file", fileName);
        try {//请求普通信息
            FormFile formfile = new FormFile(fileName, file, "file", "application/octet-stream");
            boolean tf = SocketHttpRequester.post(requestUrl, params, formfile); //上传文件
            if (tf == true) {
//                chageFileName(file.toString(), file.toString().replace("2020-", "2020aa-"));
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    public static String geturl(String url, String param) {
        String result = "";
        BufferedReader in = null;
        try {
            String urlNameString = url + "?path=" + param;
            URL realUrl = new URL(urlNameString);
            // 打开和URL之间的连接
            URLConnection connection = realUrl.openConnection();
            // 设置通用的请求属性
            connection.setRequestProperty("accept", "*/*");
            connection.setRequestProperty("connection", "Keep-Alive");
            connection.setRequestProperty("user-agent",
                    "Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1;SV1)");
            // 建立实际的连接
            connection.connect();
            // 获取所有响应头字段
            Map<String, List<String>> map = connection.getHeaderFields();
            // 遍历所有的响应头字段
            for (String key : map.keySet()) {
                System.out.println(key + "--->" + map.get(key));
            }
            // 定义 BufferedReader输入流来读取URL的响应
            in = new BufferedReader(new InputStreamReader(
                    connection.getInputStream()));
            String line;
            while ((line = in.readLine()) != null) {
                result += line;
            }
        } catch (Exception e) {
            System.out.println("发送GET请求出现异常！" + e);
            e.printStackTrace();
        }
        // 使用finally块来关闭输入流
        finally {
            try {
                if (in != null) {
                    in.close();
                }
            } catch (Exception e2) {
                e2.printStackTrace();
            }
        }
        return result;
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        int id = item.getItemId();
        if (id == R.id.action_settings) {
            return true;
        }
        return super.onOptionsItemSelected(item);
    }

    /**
     * 对文件重命名
     *
     * @param filePath 文件的路径
     */
    public void chageFileName(String filePath, String reName) {
        File file = new File(filePath);
        File newFile = new File(reName);
        file.renameTo(newFile);
    }

    @Override
    public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
        if (requestCode == MY_PERMISSIONS_REQUEST_SEND_SMS) {
            if (grantResults.length == 1 && grantResults[0] == PackageManager.PERMISSION_GRANTED) {
                // Permission Granted
            } else if (grantResults.length == 1 && grantResults[0] == PackageManager.PERMISSION_DENIED) {
                // Permission Denied
            } else {
                super.onRequestPermissionsResult(requestCode, permissions, grantResults);
            }
        }
        if (requestCode == 0x11) {
            // If request is cancelled, the result arrays are empty.
            if (grantResults.length > 0 && grantResults[0] == PackageManager.PERMISSION_GRANTED) {
                Log.i("CMCC", "权限被允许");
            } else {
                Log.i("CMCC", "权限被拒绝");
            }
        }
        if (requestCode == 102) {
            if (grantResults[0] == PackageManager.PERMISSION_GRANTED) {
                Log.i("CMCC", "权限被允许");
            } else {
                Log.i("CMCC", "权限被拒绝");
            }
        }
        switch (requestCode) {
            case SEND_SMS:
                if (grantResults[0] == PackageManager.PERMISSION_GRANTED) {
                    Log.i("CMCC", "权限被允许");
                } else {
                    // Permission Denied
                    Toast.makeText(FragmentCallActivity.this, "CALL_PHONE Denied", Toast.LENGTH_SHORT).show();
                }
                break;
            default:
                super.onRequestPermissionsResult(requestCode, permissions, grantResults);
        }
    }
}